package org.cheetah.core.action.spi;

import java.util.Arrays;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessOrder;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorOrder;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.cheetah.core.action.Action;
import org.cheetah.core.action.ActionContext;
import org.cheetah.core.action.ActionDefinition;
import org.cheetah.core.exchange.Exchange;
import org.cheetah.core.language.CompiledExpression;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
@XmlAccessorOrder(XmlAccessOrder.ALPHABETICAL)
public class SwitchCaseDefinition {

	@XmlElement(name = "value", required = true)
	private ExpressionDefinition expression;

	@XmlElementRef
	private List<ActionDefinition> then;

	@XmlTransient
	private CompiledExpression exp;

	@XmlTransient
	private Action pipeline;

	public SwitchCaseDefinition() {
		// do nothing
	}

	public SwitchCaseDefinition(ExpressionDefinition expression,
			ActionDefinition... then) {
		this.expression = expression;
		this.then = Arrays.asList(then);
	}

	private boolean equals(Object a, Object b) {
		if (a == b) {
			return true;
		}

		if ((a == null) || (b == null)) {
			return false;
		}

		return a.equals(b);
	}

	public void selfBuild() throws Exception {
		exp = expression.compile();
		pipeline = new PipelineDefinition().addAll(then).createAction();
	}

	public boolean matches(Object switchValue, Exchange exchange)
			throws Exception {
		return equals(switchValue, exp.eval(exchange));
	}

	public void process(Exchange exchange) throws Exception {
		pipeline.process(ActionContext.NOTHING, exchange);
	}
}
